const { createApp, ref, reactive, computed, onMounted, getCurrentInstance } = Vue;
const { ElMessage, ElLoading } = ElementPlus;

// 全局配置：接口地址、默认值等
const AppConfig = {
    api: {
        userInfo: '/api/welcome-info',
        sendSms: '/sendSms',
        login: '/api/login',
        register: '/api/register',
        logout: '/api/LoginOut',
        adminPanel: '/system/mall',
        products: '/api/products',       // 新增商品列表接口
        categories: '/api/categories',   // 新增分类接口
        promotions: '/api/promotions'    // 新增促销接口
    },
    defaults: {
        defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        loginPage: '/login_page'
    },
    validators: {
        phoneReg: /^1[3-9]\d{9}$/, // 手机号正则
        passwordLength: [6, 20]    // 密码长度范围
    }
};

// 工具函数
const AppUtils = {
    // 清除用户信息
    clearUserInfo: function(user, isLoggedIn) {
        document.cookie.split(';').forEach(cookie => {
            const [name] = cookie.trim().split('=');
            document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
        });

        localStorage.clear();
        sessionStorage.clear();

        user.id = null;
        user.username = '';
        user.avatar = '';
        user.role = '';
        isLoggedIn.value = false;
    },

    // 发送验证码并开始倒计时
    startCodeCountdown: async function(codeCountdown, phoneNumber) {
        try {
            if (phoneNumber===""||phoneNumber==null){
                ElMessage.error('请填写手机号');
                return
            }
            const response =  await axios.post(AppConfig.api.sendSms, {"mobile":phoneNumber}, {
                withCredentials: true
            });
            if (response.data.code===1) {
                codeCountdown.value = 60;
                const timer = setInterval(() => {
                    codeCountdown.value--;
                    if (codeCountdown.value <= 0) {
                        clearInterval(timer);
                    }
                }, 1000);

                ElMessage.success('验证码已发送，请注意查收');
            } else {
                ElMessage.error(response.data.message || '发送验证码失败');
            }
        } catch (error) {
            console.error('发送验证码出错:', error);
            ElMessage.error('网络异常，发送验证码失败');
        }
    }
};

// 应用核心逻辑
const app = createApp({
    setup() {
        // 1. 【新增】定义表单模板引用变量（必须与模板中 ref 属性值一致）
        const loginFormRef = ref(null);         // 账号密码登录表单
        const codeLoginFormRef = ref(null);     // 验证码登录表单
        const registerFormRef = ref(null);      // 注册表单
        const resetPwdFormRef = ref(null);      // 重置密码表单

        // 1. 【关键】在 setup 内部定义响应式状态（模板可访问）
        // 业务数据（初始为空数组）
        const products = ref([]);
        const categories = ref([]);
        const promotions = ref([]);

        // 加载状态（控制骨架屏/加载提示）
        const loading = reactive({
            products: false,
            categories: false,
            promotions: false
        });

        // 错误信息（接口失败时显示）
        const errors = reactive({
            products: '',
            categories: '',
            promotions: ''
        });

        // 2. 【关键】在 setup 内部定义数据加载函数
        // 本地 fallback 数据（接口失败时使用）
        const fallbackData = {
            products: [
                {
                    id: 1,
                    name: '高端智能手机',
                    description: '最新款旗舰手机，性能强劲',
                    price: 3999,
                    original_price: 4999,
                    discount: 8,
                    MainImage: 'http://59.110.50.87:6177/static/src/iPhone111_20250815183026_78069180f19a80ee.webp'
                },
                {
                    id: 2,
                    name: "智能空气净化器",
                    price: 1299,
                    original_price: 1599,
                    discount: 8,
                    MainImage: "https://images.unsplash.com/photo-1585771724684-38269d6639fd?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "高效过滤PM2.5，智能感应，静音设计，适用于30-50㎡空间"
                },
                {
                    id: 3,
                    name: "全自动咖啡机",
                    price: 899,
                    original_price: 1099,
                    discount: 8.2,
                    MainImage: "https://images.unsplash.com/photo-1511920170033-f8396924c348?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "一键制作多种咖啡，15Bar压力，自动奶泡系统"
                },
                {
                    id: 4,
                    name: "无线充电器",
                    price: 199,
                    original_price: 299,
                    discount: 6.7,
                    MainImage: "https://images.unsplash.com/photo-1585771724684-38269d6639fd?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "支持15W快充，多设备兼容，智能散热，LED指示灯"
                },
                {
                    id: 5,
                    name: "蓝牙音箱",
                    price: 399,
                    original_price: 499,
                    discount: 8,
                    MainImage: "https://images.unsplash.com/photo-1545454675-3531b543be5d?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "360°环绕音效，20小时续航，IPX7防水，支持TWS配对"
                },
                {
                    id: 6,
                    name: "电动牙刷",
                    price: 299,
                    original_price: 399,
                    discount: 7.5,
                    MainImage: "https://images.unsplash.com/photo-1551269901-5c5e14c25df7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "4种清洁模式，无线充电，30天续航，智能压力感应"
                },
                {
                    id: 7,
                    name: "智能体脂秤",
                    price: 199,
                    original_price: 259,
                    discount: 7.7,
                    MainImage: "https://images.unsplash.com/photo-1579684385127-1ef15d508118?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "精准测量13项身体数据，APP连接，最大承重150kg"
                },
                {
                    id: 8,
                    name: "便携榨汁杯",
                    price: 159,
                    original_price: 199,
                    discount: 8,
                    MainImage: "https://images.unsplash.com/photo-1499028344343-cd173ffc68a9?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "无线便携，一键榨汁，304不锈钢刀片，USB充电"
                },
                {
                    id: 9,
                    name: "颈部按摩仪",
                    price: 359,
                    original_price: 459,
                    discount: 7.8,
                    MainImage: "https://images.unsplash.com/photo-1576091160550-2173dba999ef?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80",
                    description: "仿真人手按摩，多档调节，42℃恒温热敷，15分钟自动关机"
                }
            ],
            categories: [
                { id: 1, name: "时尚服饰", icon: "fas fa-tshirt", count: 128 },
                { id: 2, name: "数码电子", icon: "fas fa-laptop", count: 96 },
                { id: 3, name: "家居生活", icon: "fas fa-home", count: 87 },
                { id: 4, name: "美食饮品", icon: "fas fa-utensils", count: 65 },
                { id: 5, name: "美妆个护", icon: "fas fa-spa", count: 72 },
                { id: 6, name: "运动户外", icon: "fas fa-running", count: 58 },
                { id: 7, name: '男鞋', icon: 'fas fa-shoe-prints', count: 228 },
                { id: 10, name: '鲜花速送', icon: 'fas fa-leaf', count: 10 },
                { id: 9, name: '女包', icon: 'fas fa-shopping-bag', count: 189 },
                { id: 8, name: '时鲜水果', icon: 'fas fa-apple-alt', count: 10 },
            ],
            promotions: [
                {
                    id: 1,
                    title: "智能手表 Pro 限时5折",
                    description: "多功能健康监测，超长续航，原价1999元，现仅需999元",
                    MainImage: "https://images.unsplash.com/photo-1523275335684-37898b6baf30?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
                },
                {
                    id: 2,
                    title: "无线降噪耳机 新品特惠",
                    description: "主动降噪，高清音质，原价899元，现仅需699元",
                    MainImage: "https://images.unsplash.com/photo-1546868871-7041f2a55e12?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
                },
                {
                    id: 3,
                    title: "夏季服饰 全场7折起",
                    description: "精选夏季新款服饰，多款可选，限时优惠",
                    MainImage: "https://images.unsplash.com/photo-1489987707025-afc232f7ea0f?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
                },
                {
                    id: 4,
                    title: '反季大促销',
                    description: '全场商品低至5折',
                    MainImage: 'http://59.110.50.87:6177/static/src/yrf222_20250815182959_231a726ec184a31d.webp'
                },
            ]
        };

        // 通用接口请求函数（内部使用 axios，确保已全局引入）
        const fetchData = async (url, dataRef, loadingKey, errorKey) => {
            try {
                loading[loadingKey] = true;
                errors[errorKey] = '';

                // 确保 axios 全局可用（HTML 中已引入 CDN）
                if (typeof window.axios === 'undefined') {
                    throw new Error('axios 未加载，请检查 CDN 链接');
                }

                // 发起接口请求（带 credentials 确保 cookie 传递）
                const response = await window.axios.get(url, {
                    withCredentials: true
                });

                // 假设接口返回格式：{ success: true, data: [...] }
                if (response.data.code===1 && response.data.message==="success") {
                    dataRef.value = response.data.data; // 赋值到响应式变量
                } else {
                    throw new Error(response.data?.message || '获取数据失败');
                }
            } catch (error) {
                console.error(`获取${errorKey}失败:`, error);
                errors[errorKey] = error.message || `加载${errorKey}时发生错误`;
                dataRef.value = fallbackData[errorKey] || []; // 用 fallback 数据兜底
            } finally {
                loading[loadingKey] = false;
            }
        };

        // 分别获取三类数据的函数
        const fetchProducts = () => fetchData(
            AppConfig.api.products,
            products,       // 对应响应式变量
            'products',     // 加载状态 key
            'products'      // 错误信息 key
        );

        const fetchCategories = () => fetchData(
            AppConfig.api.categories,
            categories,
            'categories',
            'categories'
        );

        const fetchPromotions = () => fetchData(
            AppConfig.api.promotions,
            promotions,
            'promotions',
            'promotions'
        );


        // 基础状态定义
        const currentRoute = ref('/');
        const isLoggedIn = ref(false);
        const isLoadingUserInfo = ref(false);
        const user = reactive({
            id: null,
            username: '',
            avatar: AppConfig.defaults.defaultAvatar,
            role: ''
        });

        // 登录/注册表单状态
        const loginDialogVisible = ref(false);
        const loginLoading = ref(false);
        const loginForm = reactive({
            username: '',
            password: '',
            remember: false
        });
        const loginRules = {
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
            password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
        };

        // 注册对话框
        const registerDialogVisible = ref(false);
        const registerLoading = ref(false);
        const codeCountdown = ref(0);
        const registerForm = reactive({
            username: '',
            phone: '',
            password: '',
            confirmPassword: '',
            code: ''
        });
        const registerRules = {
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
            phone: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { pattern: AppConfig.validators.phoneReg, message: '请输入正确的手机号', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                {
                    min: AppConfig.validators.passwordLength[0],
                    max: AppConfig.validators.passwordLength[1],
                    message: `长度在${AppConfig.validators.passwordLength[0]}到${AppConfig.validators.passwordLength[1]}个字符`,
                    trigger: 'blur'
                }
            ],
            confirmPassword: [
                { required: true, message: '请确认密码', trigger: 'blur' },
                {
                    validator: (rule, value, callback) => {
                        value !== registerForm.password
                            ? callback(new Error('两次输入密码不一致'))
                            : callback();
                    },
                    trigger: 'blur'
                }
            ],
            code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
        };

        // 登录方式切换相关状态
        const loginTab = ref('passwordLogin'); // 'passwordLogin' 或 'codeLogin'
        const codeLoginForm = reactive({
            phone: '',
            code: ''
        });
        const codeLoginRules = {
            phone: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { pattern: AppConfig.validators.phoneReg, message: '请输入正确的手机号', trigger: 'blur' }
            ],
            code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
        };
        const loginCodeCountdown = ref(0);

        // 重置密码相关状态
        const resetPwdDialogVisible = ref(false);
        const resetPwdLoading = ref(false);
        const resetPwdForm = reactive({
            phone: '',
            code: '',
            newPassword: '',
            confirmPassword: ''
        });
        const resetPwdRules = {
            phone: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { pattern: AppConfig.validators.phoneReg, message: '请输入正确的手机号', trigger: 'blur' }
            ],
            code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
            newPassword: [
                { required: true, message: '请输入新密码', trigger: 'blur' },
                {
                    min: AppConfig.validators.passwordLength[0],
                    max: AppConfig.validators.passwordLength[1],
                    message: `长度在${AppConfig.validators.passwordLength[0]}到${AppConfig.validators.passwordLength[1]}个字符`,
                    trigger: 'blur'
                }
            ],
            confirmPassword: [
                { required: true, message: '请确认新密码', trigger: 'blur' },
                {
                    validator: (rule, value, callback) => {
                        value !== resetPwdForm.newPassword
                            ? callback(new Error('两次输入密码不一致'))
                            : callback();
                    },
                    trigger: 'blur'
                }
            ]
        };
        const resetCodeCountdown = ref(0);

        // API请求方法
        const fetchUserInfo = async () => {
            isLoadingUserInfo.value = true;
            try {
                const response = await axios.get(AppConfig.api.userInfo, {
                    withCredentials: true
                });

                if (response.data.message && response.data.data) {
                    const userData = response.data.data;
                    isLoggedIn.value = true;
                    user.id = userData.UserNick;
                    user.username = userData.UserName;
                    user.avatar = userData.UserAvatar || AppConfig.defaults.defaultAvatar;
                    user.role = userData.UserRole|| '';

                    localStorage.setItem('user', JSON.stringify(user));
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                AppUtils.clearUserInfo(user, isLoggedIn);
            } finally {
                isLoadingUserInfo.value = false;
            }
        };

        // 发送登录验证码
        const sendLoginCode = async () => {
            try {
                if (!codeLoginForm.phone) {
                    ElMessage.error('请填写手机号');
                    return;
                }
                const response = await axios.post(AppConfig.api.sendSms, { mobile: codeLoginForm.phone }, {
                    withCredentials: true
                });
                if (response.data.code === 1) {
                    loginCodeCountdown.value = 60;
                    const timer = setInterval(() => {
                        loginCodeCountdown.value--;
                        if (loginCodeCountdown.value <= 0) {
                            clearInterval(timer);
                        }
                    }, 1000);
                    ElMessage.success('验证码已发送，请注意查收');
                } else {
                    ElMessage.error(response.data.message || '发送验证码失败');
                }
            } catch (error) {
                console.error('发送登录验证码出错:', error);
                ElMessage.error('网络异常，发送验证码失败');
            }
        };

        // 发送重置密码验证码
        const sendResetCode = async () => {
            try {
                if (!resetPwdForm.phone) {
                    ElMessage.error('请填写手机号');
                    return;
                }
                const response = await axios.post(AppConfig.api.sendSms, { mobile: resetPwdForm.phone }, {
                    withCredentials: true
                });
                if (response.data.code === 1) {
                    resetCodeCountdown.value = 60;
                    const timer = setInterval(() => {
                        resetCodeCountdown.value--;
                        if (resetCodeCountdown.value <= 0) {
                            clearInterval(timer);
                        }
                    }, 1000);
                    ElMessage.success('验证码已发送，请注意查收');
                } else {
                    ElMessage.error(response.data.message || '发送验证码失败');
                }
            } catch (error) {
                console.error('发送重置密码验证码出错:', error);
                ElMessage.error('网络异常，发送验证码失败');
            }
        };

        // 根据当前标签选择登录方式
        const handleLoginByTab = async () => {
            loginLoading.value = true;
            try {
                let response;
                // 账号密码登录
                if (loginTab.value === 'passwordLogin') {
                    // 替换为：直接使用 loginFormRef.value 访问表单
                    if (!loginFormRef.value) {
                        throw new Error('未找到登录表单');
                    }
                    await loginFormRef.value.validate(); // 验证表单

                    // 确保参数格式正确
                    const loginData = {
                        username: loginForm.username,
                        password: loginForm.password,
                        remember: loginForm.remember ? 1 : 0
                    };

                    response = await axios.post(`${AppConfig.api.login}/login_up`, loginData, {
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                }
                // 验证码登录
                else {
                    // 替换为：直接使用 codeLoginFormRef.value 访问表单
                    if (!codeLoginFormRef.value) {
                        throw new Error('未找到验证码表单');
                    }
                    await codeLoginFormRef.value.validate(); // 验证表单

                    response = await axios.post(`${AppConfig.api.login}/code`, {
                        mobile: codeLoginForm.phone,
                        sms: codeLoginForm.code
                    }, {
                        withCredentials: true,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                }

                // 检查HTTP响应状态
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                if (response.data.code===1) {
                    loginDialogVisible.value = false;
                    await fetchUserInfo();
                    ElMessage.success('登录成功');
                    // 重置表单
                    codeLoginForm.phone = '';
                    codeLoginForm.code = '';
                    loginForm.username = '';
                    loginForm.password = '';
                    loginCodeCountdown.value = 0;
                } else {
                    ElMessage.error(response.data.message || '登录失败');
                }
            } catch (error) {
                // 更详细的错误处理
                console.error('登录失败详情:', error);

                if (error.message.includes('Validation failed')) {
                    // 表单验证错误，Element Plus会自动提示
                    return;
                }

                // 处理网络错误
                if (error.message.includes('Network Error')) {
                    ElMessage.error('网络连接失败，请检查网络设置');
                    return;
                }

                // 处理404错误
                if (error.message.includes('404')) {
                    ElMessage.error('请求的接口不存在');
                    return;
                }

                // 处理500错误
                if (error.message.includes('500')) {
                    ElMessage.error('服务器内部错误，请稍后再试');
                    return;
                }

                ElMessage.error('登录失败，请重试');
            } finally {
                loginLoading.value = false;
            }
        };

        // 处理注册
        const handleRegister = async () => {
            registerLoading.value = true;
            try {
                // 替换为：直接使用 registerFormRef.value 访问表单
                if (!registerFormRef.value) {
                    throw new Error('未找到注册表单');
                }
                await registerFormRef.value.validate(); // 验证表单

                // 确保参数格式正确
                const regData = {
                    mobile: registerForm.phone,
                    nickname: registerForm.username,
                    password: registerForm.password,
                    sms: registerForm.code
                };

                const response = await axios.post(AppConfig.api.register, regData, {
                    withCredentials: true,
                    headers: { 'Content-Type': 'application/json' }
                });

                // （以下保留原有逻辑：响应处理、错误提示等）
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                if (response.data.code===1) {
                    registerDialogVisible.value = false;
                    //注册成功 直接登录
                    await fetchUserInfo();
                    // loginDialogVisible.value = true;
                    // ElMessage.success('注册成功，请登录');
                    // 重置注册表单
                    registerForm.username = '';
                    registerForm.phone = '';
                    registerForm.password = '';
                    registerForm.confirmPassword = '';
                    registerForm.code = '';
                    codeCountdown.value = 0;
                } else {
                    ElMessage.error(response.data.message || '注册失败');
                }
            } catch (error) {
                console.error('注册失败详情:', error);

                if (error.message.includes('Validation failed')) {
                    return;
                }

                if (error.message.includes('Network Error')) {
                    ElMessage.error('网络连接失败，请检查网络设置');
                    return;
                }

                ElMessage.error('注册失败，请重试');
            } finally {
                registerLoading.value = false;
            }
        };

        // 处理重置密码
        const handleResetPwd = async () => {
            resetPwdLoading.value = true;
            try {
                // 替换为：直接使用 resetPwdFormRef.value 访问表单
                if (!resetPwdFormRef.value) {
                    throw new Error('未找到重置密码表单');
                }
                await resetPwdFormRef.value.validate(); // 验证表单

                const response = await axios.post(`${AppConfig.api.login}/reset-pwd`, {
                    mobile: resetPwdForm.phone,
                    sms: resetPwdForm.code,
                    password: resetPwdForm.newPassword
                }, {
                    withCredentials: true,
                    headers: { 'Content-Type': 'application/json' }
                });

                // （以下保留原有逻辑：响应处理、错误提示等）
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                if (response.data.code===1) {
                    resetPwdDialogVisible.value = false;
                    ElMessage.success('密码重置成功，请登录');
                    // 重置表单
                    resetPwdForm.phone = '';
                    resetPwdForm.code = '';
                    resetPwdForm.newPassword = '';
                    resetPwdForm.confirmPassword = '';
                    resetCodeCountdown.value = 0;
                } else {
                    ElMessage.error(response.data.message || '密码重置失败');
                }
            } catch (error) {
                console.error('重置密码失败详情:', error);

                if (error.message.includes('Validation failed')) {
                    return;
                }

                if (error.message.includes('Network Error')) {
                    ElMessage.error('网络连接失败，请检查网络设置');
                    return;
                }

                ElMessage.error('重置密码失败，请重试');
            } finally {
                resetPwdLoading.value = false;
            }
        };

        // 退出登录
        const logout = async () => {
            if(confirm('确定要退出登录吗？')) {
                try {
                    await axios.post(AppConfig.api.logout, {}, {
                        withCredentials: true
                    });
                    AppUtils.clearUserInfo(user, isLoggedIn);
                    ElMessage.success('已退出登录');
                } catch (error) {
                    console.error('退出登录失败:', error);
                    AppUtils.clearUserInfo(user, isLoggedIn);
                    ElMessage.success('已退出登录');
                }
            }
        };

        // 页面交互方法
        const goToLogin = () => {
            loginDialogVisible.value = true;
            registerDialogVisible.value = false;
        };
        const goToRegister = () => {
            registerDialogVisible.value = true;
            loginDialogVisible.value = false;
        };

        const goToProfile = () => {
            if (!isLoggedIn.value) return goToLogin();
            const collectUrl = '/userinfo'; // 用户信息地址
            window.open(collectUrl, 'userinfo');
        };

        const goToAdminPanel = () => {
            if (user.role === 'super_admin') {
                window.location.href = AppConfig.api.adminPanel;
            } else {
                ElMessage.warning('您没有超级管理员权限');
            }
        };

        const showProductDetail = (product) => {
            if (!isLoggedIn.value) return goToLogin();
            ElMessage.success(`查看商品: ${product.name}`);
            const collectUrl = '/product'; // 用户信息地址
            window.open(collectUrl, 'product');
        };

        const getPtdId = async (product) => {
            const collectUrl = '/get/product/desc';
            const response = await axios.get(collectUrl, {
                params: {
                    id: product.category_id,
                },
                withCredentials: true,
            });

            if (response.status < 200 || response.status >= 300) {
                throw new Error(`HTTP错误: ${response.status}`);
            }
            return null
        }

        const navigateTo = (route) => {
            currentRoute.value = route;
            let targetId = '';

            switch(route) {
                case '/':
                    targetId = 'hero';
                    break;
                case '/categories':
                    targetId = 'categories-section';
                    break;
                case '/new-arrivals':
                    targetId = 'products-section';
                    break;
                case '/promotions':
                    targetId = 'promotions-section';
                    break;
                case '/about':
                    targetId = 'about-section';
                    break;
            }

            const targetElement = document.getElementById(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 70,
                    behavior: 'smooth'
                });
            }
        };

        // 初始化逻辑
        onMounted(async () => {
            // 并行加载三类业务数据（同时请求，提升性能）
            await Promise.all([
                fetchProducts(),
                fetchCategories(),
                fetchPromotions()
            ]);
            fetchUserInfo().then(r => console.log(r));
            window.addEventListener('scroll', updateCurrentRouteOnScroll);
        });

        const updateCurrentRouteOnScroll = () => {
            const scrollPosition = window.scrollY + 100;

            const sections = [
                { id: 'hero', route: '/' },
                { id: 'products-section', route: '/new-arrivals' },
                { id: 'categories-section', route: '/categories' },
                { id: 'promotions-section', route: '/promotions' },
                { id: 'footer', route: '/about' }
            ];

            for (const section of sections) {
                const element = document.getElementById(section.id);
                if (element) {
                    const offsetTop = element.offsetTop;
                    const offsetBottom = offsetTop + element.offsetHeight;

                    if (scrollPosition >= offsetTop && scrollPosition < offsetBottom) {
                        currentRoute.value = section.route;
                        break;
                    }
                }
            }
        };

        // 暴露给模板的变量/方法
        return {
            // 【新增】表单模板引用（必须添加，否则模板无法绑定）
            loginFormRef,
            codeLoginFormRef,
            registerFormRef,
            resetPwdFormRef,

            currentRoute,
            isLoggedIn,
            user,
            isLoadingUserInfo,
            loginDialogVisible,
            loginForm,
            loginRules,
            loginLoading,
            registerDialogVisible,
            registerForm,
            registerRules,
            registerLoading,
            codeCountdown,
            products,
            categories,
            promotions,

            // 登录方式切换相关
            loginTab,
            codeLoginForm,
            codeLoginRules,
            loginCodeCountdown,

            // 重置密码相关
            resetPwdDialogVisible,
            resetPwdForm,
            resetPwdRules,
            resetPwdLoading,
            resetCodeCountdown,

            // 数据相关状态（必须暴露，模板才能访问）
            loading,        // 加载状态
            errors,         // 错误信息

            // 数据刷新方法（可选，供模板手动刷新）
            refreshProducts: fetchProducts,
            refreshCategories: fetchCategories,
            refreshPromotions: fetchPromotions,

            goToLogin,
            goToRegister,
            goToProfile,
            goToAdminPanel,
            sendCode: () => AppUtils.startCodeCountdown(codeCountdown, registerForm.phone),
            handleLoginByTab,
            handleRegister,
            logout,
            showProductDetail,
            navigateTo,
            sendLoginCode,
            sendResetCode,
            handleResetPwd
        };
    }
});

app.use(ElementPlus);
app.mount('#app');